package com.framework.bdf4j.comm.util;

import java.util.Collection;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import com.framework.bdf4j.comm.SpringContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * Cache工具类
 * 
 */
@Slf4j
public class CacheUtils {

    private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);

    /**
     * 从缓存中移除
     * 
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, String key) {
        getCache(cacheName).evict(key);
    }

    /**
     * 从缓存中移除所有
     * 
     * @param cacheName
     */
    public static void removeAll(String cacheName) {
        Cache cache = getCache(cacheName);
        cache.clear();
        log.info("清理缓存： {} ", cacheName);
    }

    /**
     * 获取缓存
     * 
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key) {
        return getCache(cacheName).get(key);
    }

    /**
     * 获得一个Cache，没有则显示日志。
     * 
     * @param cacheName
     * @return
     */
    public static Cache getCache(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new RuntimeException("当前系统中没有定义“" + cacheName + "”这个缓存。");
        }
        return cache;
    }

    /**
     * 获取所有缓存
     * 
     * @return 缓存组
     */
    public static String[] getCacheNames() {
        Collection<String> ches = cacheManager.getCacheNames();
        return ches.toArray(new String[0]);
    }
}
